const router = require("express")();
const dm = require("../core/DataManager");
const um = require("../core/UserManager");
const HotCounter = require("../core/Counter").HotCounter.get;
const tool = NCUTCAT.tools;

//获取相关关系
router.all("/relation/:id", async (req, res) => {
    dm.getCatRelation((req.params || {}).id || 0, DM_RES(res, undefined, 'error'))
});

let CatAll__ = null;
let CatAll__TIME = 0;
const dgcact = NCUTCAT.localProperty.database_getCatAll_cache_threshold;
//获取所有猫咪信息
router.all("/get/all", async function(req, res) {
    const time = new Date().getTime();
    if (CatAll__ && time - CatAll__TIME < dgcact) return res.json(RES_CHECKER({ success: true, result: CatAll__, cacheTime: time, age: dgcact }));
    dm.getCatAll(DM_RES(res, undefined, 'error', result => CatAll__ = result));
});

//搜索一只猫咪
router.all("/get/id/:v", async function(req, res) {
    let value = (req.params || {}).v || "";
    value = decodeURI(value);
    dm.getCatByID(value, DM_RES(res, undefined, 'error'));
});

//创建一只猫咪
router.post("/create", um.middle_checker, um.middle_loadUser, async function(req, res) {
    let user = req.user;
    if (um.permissionCheck(true, user, 'create_cat')) {
        let param = req.body || {};
        let badNode = await checkUploadData(param);
        if (badNode) return res.json(RES_CHECKER({ success: false, err: "数据错误", node: badNode }));
        else {
            CatAll__ = null;
            dm.createCat(param, DM_RES(res));
        }
    } else return res.json(RES_CHECKER({ success: false, err: "没有足够的权限" }));
});

//更新一只猫咪
router.post("/update", um.middle_checker, um.middle_loadUser, async function(req, res) {
    let user = req.user;
    if (um.permissionCheck(true, user, 'update_cat')) {
        let param = req.body || {};
        let badNode = await checkUploadData(param);
        if (badNode) return res.json(RES_CHECKER({ success: false, err: "数据错误", node: badNode }));
        else {
            CatAll__ = null;
            dm.updateCat(param, DM_RES(res, undefined, 'error'));
        }
    } else return res.json(RES_CHECKER({ success: false, err: "没有足够的权限" }));
});

//删除一只猫咪
router.get("/remove/:id", um.middle_checker, um.middle_loadUser, async function(req, res) {
    let user = req.user;
    if (um.permissionCheck(true, user, 'remove_cat')) {
        let params = req.params || {};
        let id = params.id || "-1";
        if (!((id = parseInt(id)) >= 0)) return res.json(RES_CHECKER({ success: false, err: "数据错误", id: id }));
        else {
            CatAll__ = null;
            dm.removeCat(id, DM_RES(res, undefined, 'error'));
        }
    } else return res.json(RES_CHECKER({ success: false, err: "没有足够的权限" }));
});

router.get('/hot', async (req, res) => {
    res.json(HotCounter());
});

async function checkUploadData(d) {
    let K = dm.table_key,
        V = dm.table_value['basic_info'],
        C = { img: t => dm.hasCatImg(t), str: t => typeof t === 'string' && t.length < 255, age: t => tool.isDate(t, true), date: t => tool.isDate(t), enum: (t, k) => t in (V[K[k].v] || {}) };
    for (let k in K) {
        if (K[k].t !== 'basic_info' || !K[k].c) continue;
        if (d[k] === '' || d[k] === undefined) continue;
        let H = C[K[k].c];
        console.log(K[k], K[k].c, H);
        if ((H.constructor.name === 'AsyncFunction') ? await H(d[k], k) : H(d[k], k)) continue;
        return k;
    }
    return false;
}


//模块导出
module.exports = router;